package com.example.kabaouser.Utils;

import com.example.kabaouser.config.QiniuConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.FileInputStream;

public class QiniuUtil {

    public String uploadQNImg(FileInputStream file, String key, QiniuConfig qiniuConfig) {

        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            Auth auth = Auth.create(qiniuConfig.getAccessKey(),qiniuConfig.getSecretKey());
            String token = auth.uploadToken(qiniuConfig.getBucket());
            try {
                Response response = uploadManager.put(file,key,token,null,null);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
                String returnPath = qiniuConfig.getPath() + "/" + putRet.key;
                return returnPath;
            }catch (QiniuException e) {
                Response r = e.response;
                System.err.println(r.toString());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
